package org.yuyao.security.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.yuyao.security.annotation.RequiresLogin;
import org.yuyao.security.annotation.RequiresPermissions;
import org.yuyao.security.annotation.RequiresRoles;

import java.lang.reflect.Method;


/**
 * 权限切面检查
 */
@Aspect
@Component
public class PreAuthorizeAspect implements Ordered {
    private  final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final static String POINTCUT="@annotation(org.yuyao.security.annotation.RequiresLogin)||@annotation(org.yuyao.security.annotation.RequiresRoles)||@annotation(org.yuyao.security.annotation.RequiresPermissions)";


    @Pointcut(POINTCUT)
    public void ponitCut(){}

    @Around("ponitCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature ms= (MethodSignature) joinPoint.getSignature();
        checkPermission(ms);
        try {
            Object result=joinPoint.proceed();
            return result;
        } catch (Throwable e) {
            throw e;
        }
    }

    /**
     * 检查权限
     * @param ms
     */
    private void checkPermission(MethodSignature ms) {
        Method method= ms.getMethod();
        RequiresLogin requiresLogin= method.getAnnotation(RequiresLogin.class);
        if(requiresLogin!=null){
            //TODO 检查是否登录();
            logger.info("检查是否需要登录:{}",method.getName());
        }
        RequiresRoles requiresRoles= method.getAnnotation(RequiresRoles.class);
        if(requiresRoles!=null){
            //TODO 检查是否拥有角色
            logger.info("检查是否拥有角色:{}",method.getName());
        }
        RequiresPermissions requiresPermissions= method.getAnnotation(RequiresPermissions.class);
        if(requiresPermissions!=null){
            //TODO 检查是否拥有权限
            logger.info("检查是否拥有权限:{}",method.getName());
        }

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+1;
    }
}
